<template>
  <div id="user-information-completion">
    <div class="main-container container-limited container-fluid page-holder">
      <div class="easy-container-x2 border-bottom"></div>
      <el-row :gutter="30" class="easy-container-x2">
        <el-col :md="8">
          <h3 class="m-t-0">完善用户信息</h3>
        </el-col>
        <el-col :md="16">
          <el-form ref="infoCompleteForm" label-position="top" class="bold-label"
                   :model="form" :rules="rules">
            <el-form-item label="身份" prop="identity" ref="identity">
              <el-select v-model="form.identity">
                <el-option v-for="identity in $C.users.identities" :key="identity.value"
                           :value="identity.value" :label="identity.cn"/>
              </el-select>
            </el-form-item>
            <el-form-item label="学校或单位" prop="company" ref="company">
              <el-autocomplete v-model="form.company" :trigger-on-focus="false" value-key="name"
                               placehoder="请输入学校或单位" :disabled="!form.identity"
                               :fetch-suggestions="companyMatching"
                               @select="companySelect" @blur="companyBlur"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit" :loading="isLoading">保存</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import * as format from './format';

export default {
  name: 'InfoCompletion', // 完善用户信息
  data() {
    return {
      form: {
        identity: null, // 身份
        company: null, // 学校或单位
        companyCode: null, // 学校识别码
      },
      rules: {
        identity: [{ required: true, message: '身份不能为空', trigger: ['blur', 'change'] }],
        company: [{ required: true, message: '学校或单位不能为空', trigger: ['blur', 'change'] }],
      },
      isLoading: false, // 正在保存个人信息
    };
  },
  computed: {
    // 完善用户信息所需参数
    initUpdateParams() {
      return {
        id: this.$store.state.currentUser.id,
        identity: this.form.identity,
        company: ['teacher', 'student'].includes(this.form.identity) ? this.form.companyCode : this.form.company,
      };
    },
  },
  methods: {
    // 匹配学校或单位
    companyMatching(value, cb) {
      if (!this.$C.users.idMatchSchool.includes(this.form.identity)) cb([]);
      else {
        this.$api.other.companyMatching({ title: value.trim() })
          .then(res => cb(res.data)).catch(() => {});
      }
    },
    // 选择学校
    companySelect(obj) { this.form.companyCode = obj.code; },
    // 非正常操作会清空选项
    companyBlur() {
      if (this.$C.users.idMatchSchool.includes(this.form.identity)) {
        this.form.company = '';
        this.form.companyCode = '';
      }
    },
    // 保存用户信息
    onSubmit() {
      this.$refs.infoCompleteForm.validate((valid, errs) => {
        if (valid) {
          this.isLoading = true;
          this.$api.users.update(this.initUpdateParams)
            .then((res) => {
              this.$message.success('保存成功');
              const userData = Object.assign(format.formatUser(res.data), {
                token: this.$store.state.currentUser.token,
              });
              this.$store.dispatch('setCurrentUser', userData);
              this.$router.push(this.$route.query.redirect || '/');
            })
            .catch(() => {})
            .then(() => { this.isLoading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
  },
};
</script>

<style></style>
